/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.imagepipeline.bitmaps;

import com.facebook.common.internal.Preconditions;
import com.facebook.common.references.CloseableReference;
import com.facebook.imagepipeline.core.CloseableReferenceFactory;
import com.facebook.imagepipeline.memory.BitmapPool;
import com.facebook.imageutils.BitmapUtil;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;

import javax.annotation.concurrent.ThreadSafe;

/**
 * Bitmap factory for ART VM (Lollipop and up).
 */
@ThreadSafe
public class ArtBitmapFactory extends PlatformBitmapFactory {
    private final String TAG = ArtBitmapFactory.class.getSimpleName();

    private final BitmapPool mBitmapPool;
    private final CloseableReferenceFactory mCloseableReferenceFactory;

    public ArtBitmapFactory(
            BitmapPool bitmapPool, CloseableReferenceFactory closeableReferenceFactory) {
        mBitmapPool = bitmapPool;
        mCloseableReferenceFactory = closeableReferenceFactory;
    }

    /**
     * Creates a bitmap of the specified width and height.
     *
     * @param width        the width of the bitmap
     * @param height       the height of the bitmap
     * @param bitmapConfig the  used to create the decoded
     *                     Bitmap
     * @return a reference to the bitmap
     * @throws OutOfMemoryError if the Bitmap cannot be allocated
     */
 /* @Override
  public CloseableReference<PixelMap> createBitmapInternal(int width, int height, Bitmap.Config bitmapConfig) {
    int sizeInBytes = BitmapUtil.getSizeInByteForBitmap(width, height, bitmapConfig);
    PixelMap bitmap = mBitmapPool.get(sizeInBytes);
    Preconditions.checkArgument(
        bitmap.getAllocationByteCount()
            >= width * height * BitmapUtil.getPixelSizeForBitmapConfig(bitmapConfig));
    bitmap.reconfigure(width, height, bitmapConfig);
    return mCloseableReferenceFactory.create(bitmap, mBitmapPool);
  }*/
    @Override
    public CloseableReference<PixelMap> createBitmapInternal(int width, int height, PixelFormat bitmapConfig) {
        int sizeInBytes = BitmapUtil.getSizeInByteForBitmap(width, height, bitmapConfig);
        PixelMap bitmap = mBitmapPool.get(sizeInBytes);
        Preconditions.checkArgument(
                bitmap.getPixelBytesNumber()
                        >= width * height * BitmapUtil.getPixelSizeForBitmapConfig(bitmapConfig));
        Size size = new Size();
        size.width = width;
        size.height = height;
        bitmap.resetConfig(size, bitmapConfig);
        return mCloseableReferenceFactory.create(bitmap, mBitmapPool);
    }
}
